<template>
  <el-form :model="form" :rules="rules" ref="form">
    <el-form-item label="当前密码" prop="oldPwd">
      <el-input type="password" v-model.trim="form.oldPwd" />
    </el-form-item>
    <el-form-item label="新密码" prop="newPwd">
      <el-input type="password"  v-model.trim="form.newPwd" />
    </el-form-item>
    <el-form-item label="确认密码" prop="newConfirmPwd">
      <el-input type="password"  v-model.trim="form.newConfirmPwd" />
    </el-form-item>    
    <el-form-item>
      <el-button type="primary" @click="submit('form')">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { modifyMyPwd } from '@/api/admin/user/index'
export default {
  data() {
    const validateConfirmPass = (rule, value, callback) => {
      if (!value || value.length < 5) {
        callback(new Error('确认密码不能小于5位'));
      } 
      else if(!this.form.newPwd || this.form.newPwd != value) {
        callback(new Error('确认密码不正确'));
      }
      else {
        callback();
      }
    };    
    return {
      form: {
        oldPwd: undefined,
        newPwd: undefined,
        newConfirmPwd: undefined
      },
      
      rules: {
        oldPwd: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ],
        newPwd: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ],
        newConfirmPwd: [
          {
            required: true,
            trigger: 'blur',
            validator: validateConfirmPass
          }
        ]
      },
      sexOptions: ['男', '女']
    }
  },
  methods: {
    submit(formName) {
      //验证表单
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
           modifyMyPwd(this.form).then(response => {
           if(response.status === 0){
              this.$refs[formName].resetFields();
              this.$message.success('修改成功');
           }
          else{
            this.$message.error(response.message);
          }
         });
        } else {
          return false;
        }
      });
    }
  }
}
</script>
